﻿using Casamiel.API.Application.Commands;
using Casamiel.API.Application.Models;
using Casamiel.API.Application.Services;
using Casamiel.API.Infrastructure;
using Casamiel.API.Infrastructure.Filters;
using Casamiel.Application;
using Casamiel.Common;
using Casamiel.Common.Extensions;
using Casamiel.Domain;
using Casamiel.Domain.Entity;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using MediatR;
using Casamiel.Domain.Response;
using System.Globalization;
using Casamiel.Domain.Response.IC;
using Casamiel.API.Application;

namespace Casamiel.API.Controllers.V1
{
    /// <summary>
    /// 
    /// </summary>
    [Produces("application/json")]
    [ApiVersion("1.0")]
    [Route("api/v{api-version:apiVersion}/[controller]")]
    [Authorize]
    [TypeFilterAttribute(typeof(CheckLoginAttribute))]
    [ApiController]
    public class CardController : BaseController
    {
        private readonly IIcApiService _iicApiService;
        private readonly ICacheService _cacheService;
        private readonly IMemberCardService _memberCard;
        private readonly IMobileCheckCode _mobileCheckCode;
        private readonly CasamielSettings _settings;
        private readonly IUserLogService _userLog;
        //private readonly NLog.ILogger logger = LogManager.GetLogger("IicApiService");
        private readonly IMediator _mediator;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="settings"></param>
        /// <param name="iicApiService"></param>
        /// <param name="cacheService"></param>
        /// <param name="memberCard"></param>
        /// <param name="mobileCheckCode"></param>
        /// <param name="userLog"></param>
        /// <param name="mediator"></param>
        public CardController(IOptionsSnapshot<CasamielSettings> settings, IIcApiService iicApiService, //CasamielContext context,
            ICacheService cacheService,
            IMemberCardService memberCard,
            IMobileCheckCode mobileCheckCode,
            IUserLogService userLog, IMediator mediator)
        {
            if (settings == null) {
                throw new ArgumentNullException(nameof(settings));
            }

            _settings = settings.Value;
            _iicApiService = iicApiService;
            _cacheService = cacheService;
            _memberCard = memberCard;
            _mobileCheckCode = mobileCheckCode;
            _userLog = userLog;
            _mediator = mediator;
        }
        /// <summary>
        /// 我的会员券
        /// </summary>
        /// <param name="data"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        ///<remarks>
        ///1、	返回数据内容：
        ///{"code":0,"msg":"处理成功",
        ///"content":"{"cardno":"xxx","phoneno":"xxx","wxopenid":"xxx",
        ///"tickets":[{"cardno":"卡号","ticketid":xxxx,"ticketname":"券名称","tickettype":"券类型","source":"券来源方式","state":1,"je":xxx.xx,"makedate","2016-01-08""startdate","2016-01-08""enddate","2016-10-08","prange":[{"pid":xxx,"count":xxx},{"pid":xxx,"count":xxx},……]},
        ///{"cardno":"xxxx","ticketid":xxxx,"ticketname":"周年庆券","tickettype":"充值赠送券","source":"微信","state":1,
        ///"je":xxx.xx,"makedate","2016-01-08""startdate","2016-01-08""enddate","2016-10-08","prange":[{"pid":xxx,"count":xxx},{"pid":xxx,"count":xxx},……]},……]}","sign":"9ade8ba90cf38745bea56398d235daae"}
        ///</remarks>
        [HttpPost]
        [Route("[action]")]
        [ProducesResponseType(typeof(Zmodel), (int)HttpStatusCode.OK)]
        [ProducesResponseType((int)HttpStatusCode.NotFound)]
        public async Task<IActionResult> GetTicticket([FromBody] CardReq data, [FromHeader(Name = "u-token")] string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            var hascard = await HasCard(token, data.cardno).ConfigureAwait(false);
            if (!hascard) {
                return new JsonResult(new { code = -1, content = "", msg = "无此卡" });
            }
            var a = await _iicApiService.icticket(data.cardno).ConfigureAwait(false);
            var rnt = JsonConvert.DeserializeObject<JObject>(a.content);
            var n = new { code = a.code, content = rnt, msg = a.msg, sysdate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.CurrentCulture) };
            return new JsonResult(n);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="token"></param>
        /// <param name="cardno"></param>
        /// <returns></returns>
        private async Task<bool> HasCard(string token, string cardno)
        {
            var mobile = MemberHelper.GetMobile(token);
            var list   = await _memberCard.GetListAsync<ICasaMielSession>(mobile).ConfigureAwait(false);
            if (list == null || !list.Any(c => c.CardNO == cardno && c.IsBind == true)) {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 操作记录（自动加手机号验证）
        /// </summary>
        /// <param name="data"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        [ProducesResponseType(typeof(Zmodel), (int)HttpStatusCode.OK)]
        [ProducesResponseType((int)HttpStatusCode.NotFound)]
        public async Task<IActionResult> Icstatequery([FromBody] CardReq data, [FromHeader(Name = "u-token")] string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            var hascard = await HasCard(token, data.cardno).ConfigureAwait(false);
            if (hascard) {
                var a = await _iicApiService.Icstatequery(data.cardno).ConfigureAwait(false);
                var rnt = JsonConvert.DeserializeObject<JObject>(a.content);
                var n = new { code = a.code, content = rnt, msg = a.msg };
                return new JsonResult(n);
            } else {
                return new JsonResult(new { code = -1, content = "", msg = "无此卡" });
            }
        }
        /// <summary>
        /// 我的会员卡
        /// </summary>
        /// <param name="token">用户token必填</param>
        /// <returns></returns>
        /// <remarks>
        /// {
        ///"code":0,
        ///"msg":"处理成功",
        ///"content":"
        ///{
        ///"cardno":"xxxxxx",
        ///"wxopenid":"xxxx",
        ///"totalmoney":xx.xx,
        ///"directmoney":xx.xx,
        ///"othermoney":x.xx,
        ///”point”:xxx,
        ///“tickets”:
        ///[
        ///{
        ///"ticketname":"xxxx",
        ///"je":xxx.xx,
        ///"makedate","yyyy-mm-dd",
        ///"startdate","yyyy-mm-dd",
        ///"enddate","yyyy-mm-dd",
        ///"description",""	
        /// },
        ///{
        ///"ticketname":"xxxx",
        ///"je:xxx.xx,
        ///"makedate”,"yyyy-mm-dd",
        ///"startdate”,"yyyy-mm-dd",
        ///"enddate","yyyy-mm-dd",
        ///"description",""	
        ///  }
        ///]
        ///}”,
        ///"sign":"9ade8ba90cf38745bea56398d235daae"
        ///}
        /// </remarks>
        [HttpPost]
        [HttpGet]
        [Route("[action]")]
        [ProducesResponseType(typeof(Zmodel), (int)HttpStatusCode.OK)]
        [ProducesResponseType((int)HttpStatusCode.NotFound)]
        public async Task<ActionResult<BaseResult<List<CardInfoResponse>>>> GetMyCard([FromHeader(Name = "u-token")] string token)
        {
            var mobile = MemberHelper.GetMobile(token);

            var command = new GetMyCardCommand(mobile, 15) { RequestUrl = Request.GetShortUri(), UserIP = Request.GetUserIp() };
            var result = await _mediator.Send(command).ConfigureAwait(false);
            return result;
            #region MyRegion
            //var card = _context.MemberCard.Where(c => c.Mobile == mobile && c.IsBind == true).FirstOrDefault();
            /*
            var list = _cacheService.Get<List<MemberCard>>(Constant.MYCARDS_PREFIX + mobile);
            if (_settings.CacheEnable)
            {
                if (list == null)
                {
                    list = await _memberCard.GetCardListAsyncByMobile<ICasaMielSession>(mobile);
                    if (list != null)
                    {
                        _cacheService.Add(Constant.MYCARDS_PREFIX + mobile, list, TimeSpan.FromMinutes(10), true);
                    }
                }
            }
            else
            {
                list = await _memberCard.GetCardListAsyncByMobile<ICasaMielSession>(mobile);
            }
            //await _memberCard.GetCardListAsyncByMobile(mobile);
            var mycard = list.Where(a => a.IsBind == true);
            List<CardInfoResponse> cardlist = new List<CardInfoResponse>();
            foreach (var item in mycard)
            {
                var a = await _iicApiService.GetCardBalance(item.CardNo);
                var rnt = JsonConvert.DeserializeObject<JObject>(a.content);
                if (a.code == 0 || a.code == 8)
                {
                    cardlist.Add(new CardInfoResponse
                    {
                        cardno = item.CardNo,
                        totalmoney = rnt == null ? "0" : rnt["totalmoney"].ToString(),
                        cardtype = item.CardType,
                        othermoney = rnt == null ? "0" : rnt["othermoney"].ToString(),
                        directmoney = rnt == null ? "0" : rnt["directmoney"].ToString(),
                        point = rnt == null ? "0" : rnt["point"].ToString()
                    });
                }
                else if (a.code == 90 || a.code == -7)
                {
                    CardRefreshDto data = new CardRefreshDto { cardno = item.CardNo, phoneno = mobile, startdate = DateTime.Now.ToString("yyyy-MM-dd 00:00:00") };
                    var result = await _iicApiService.icrefresh(data);
                    logger.Trace($"CardRefresh:{JsonConvert.SerializeObject(result)}");
                    if (result.code == 0)
                    {
                        var jcard = JsonConvert.DeserializeObject<JObject>(result.content);
                        //var mcard = await _memberCard.FindAsyncByCardnoMobile<ICasaMielSession>(item.CardNo, mobile);
                        var clist = await _memberCard.GetCardListAsyncByMobile<ICasaMielSession>(mobile);
                        var mcard = clist.Where(c => c.CardType == "1" && c.IsBind == true).SingleOrDefault();
                        if (mcard != null)
                        {
                            mcard.CardNo = jcard["newcardno"].ToString();
                            mcard.BindTime = DateTime.Now;
                            await _memberCard.UpdateAsync<ICasaMielSession>(mcard);
                        }
                        mcard = new MemberCard();
                        mcard.CardNo = jcard["newcardno"].ToString();
                        mcard.Mobile = mobile;
                        mcard.IsBind = true;
                        mcard.CardType = "1";
                        mcard.State = 1;
                        mcard.BindTime = DateTime.Now;
                        mcard.CreateTime = DateTime.Now;
                        await _memberCard.AddAsync<ICasaMielSession>(mcard);
                        var logdata = new UserLog { Url = Request.GetAbsoluteUri(), OPInfo = $"补会员卡,原卡号:[{item.CardNo}，新卡号：{mcard.CardNo}", OPTime = DateTime.Now, UserName = mobile, UserIP = Request.GetUserIp() };
                        await _userLog.AddAsync<ICasaMielSession>(logdata);

                        var czmodel = await _iicApiService.GetCardBalance(mcard.CardNo);
                        _cacheService.Remove(Constant.MYCARDS_PREFIX + mobile);

                        if (czmodel.code == 0 || czmodel.code == 8)
                        {
                            var cardinfo = JsonConvert.DeserializeObject<JObject>(czmodel.content);
                            cardlist.Add(new CardInfoResponse
                            {
                                cardno = mcard.CardNo,
                                totalmoney = rnt == null ? "0" : cardinfo["totalmoney"].ToString(),
                                cardtype = item.CardType,
                                state = item.State.ToString(),
                                othermoney = rnt == null ? "0" : cardinfo["othermoney"].ToString(),
                                directmoney = rnt == null ? "0" : cardinfo["directmoney"].ToString(),
                                point = rnt == null ? "0" : cardinfo["point"].ToString()
                            });
                        }
                    }
                }
                else
                {
                    cardlist.Add(new CardInfoResponse
                    {
                        cardno = item.CardNo,
                        totalmoney = "0",
                        cardtype = item.CardType,
                        othermoney = "0",
                        directmoney = "0",
                        point = "0"
                    });
                }
            }
            return new JsonResult(new { code = 0, content = cardlist });
            */


            #endregion
        }

        /// <summary>
        /// 判断是否可以充值金额
        /// </summary>
        /// <param name="data"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        /// <remarks>
        /// {"code": 0,"content": "","msg": "最多还能充值¥2,390.00"}</remarks>
        [HttpPost]
        [Route("[action]")]
        [ProducesResponseType((int)HttpStatusCode.NotFound)]
        public async Task<IActionResult> CheckChargeLimit([FromBody] CheckChargeLimitReq data, [FromHeader(Name = "u-token")] string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            var mobile = MemberHelper.GetMobile(token);

            var mcard = await _memberCard.FindAsync<ICasaMielSession>(data.cardno, mobile).ConfigureAwait(false);
            if (mcard != null && mcard.CardNO == data.cardno) {
                var a = await _iicApiService.GetCardBalance(data.cardno,$"{LoginInfo.Item3}099".ToInt32(0)).ConfigureAwait(false);
                var rnt = JsonConvert.DeserializeObject<JObject>(a.content);
                if (a.code == 0) {
                    decimal je = Convert.ToDecimal(rnt["totalmoney"].ToString(), CultureInfo.CurrentCulture);
                    if ((je + data.chargeAmount) < 2500) {
                        return new JsonResult(new { code = 0, content = "", msg = "可以充值" });//todo:充值规则
                    } else {
                        return new JsonResult(new { code = 0, content = "", msg = $"最多还能充值{(2500 - je).ToString("C2", CultureInfo.CurrentCulture)}" });
                    }
                }

                var n = new { code = a.code, content = rnt, msg = a.msg };
                return new JsonResult(n);
            } else {
                return new JsonResult(new { code = -1, content = "", msg = "无此卡" });
            }
        }
        /// <summary>
        /// 会员卡余额
        /// </summary>
        /// <param name="token">用户token</param>
        /// <param name="card">卡信息</param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        [ProducesResponseType(typeof(Zmodel), (int)HttpStatusCode.OK)]
        [ProducesResponseType((int)HttpStatusCode.NotFound)]
        public async Task<IActionResult> GetBalance([FromBody] CardReq card,
        [FromHeader(Name = "u-token")]  string token)
        {
            if (card == null) {
                throw new ArgumentNullException(nameof(card));
            }

            var mobile = MemberHelper.GetMobile(token);
            var list = await _memberCard.GetListAsync<ICasaMielSession>(mobile).ConfigureAwait(false);
                if (list != null) {
                    _cacheService.Add(Constant.MYCARDS_PREFIX + mobile, list, TimeSpan.FromMinutes(10), true);
                }
           

            if (list == null || !list.Where(c => c.CardNO == card.cardno && c.IsBind == true).Any()) {
                return new JsonResult(new { code = -1, content = "", msg = "无此卡" });
            }
            var a = await _iicApiService.GetCardBalance(card.cardno,$"{LoginInfo.Item3}099".ToInt32(0)).ConfigureAwait(false);
            var rnt = JsonConvert.DeserializeObject<JObject>(a.content);
            var n = new { code = a.code, content = rnt, msg = a.msg };
            return new JsonResult(n);

        }

        /// <summary>
        ///取余额 --测试用
        /// </summary>
        /// <param name="cardno"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> GetBalanceTest(string cardno, [FromHeader(Name = "u-token")]  string token)
        {
            var a = await _iicApiService.GetCardBalance(cardno, $"{LoginInfo.Item3}099".ToInt32(0)).ConfigureAwait(false);
            var rnt = JsonConvert.DeserializeObject<JObject>(a.content);
            var n = new { code = a.code, content = rnt, msg = a.msg };
            return new JsonResult(n);
        }
        /// <summary>
        /// 操作记录
        /// </summary>
        /// <param name="token">用户token</param>
        /// <param name="data">卡信息</param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        [ProducesResponseType(typeof(Zmodel), (int)HttpStatusCode.OK)]
        [ProducesResponseType((int)HttpStatusCode.NotFound)]
        public async Task<IActionResult> GetOpration([FromBody]CardReq data, [FromHeader(Name = "u-token")]  string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            var hascard = await HasCard(token, cardno: data.cardno).ConfigureAwait(false);
            if (hascard == false) {
                return new JsonResult(new { code = -1, content = "", msg = "无此卡" });
            }
            var a = await _iicApiService.Icstatequery(data.cardno).ConfigureAwait(false);
            var rnt = JsonConvert.DeserializeObject<JObject>(a.content);

            var n = new { code = a.code, content = rnt, msg = a.msg };
            return new JsonResult(n);
        }
        /// <summary>
        /// 消费码
        /// </summary>
        /// <param name="data">卡信息</param>
        /// <param name="token">用户token</param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        [ProducesResponseType(typeof(Zmodel), (int)HttpStatusCode.OK)]
        [ProducesResponseType((int)HttpStatusCode.NotFound)]
        public async Task<IActionResult> Getconsumecode([FromBody]CardReq data, [FromHeader(Name = "u-token")]  string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            ConsoleHelper.DoLog(data, Request);
            var hascard = await HasCard(token, data.cardno).ConfigureAwait(false);
            if (hascard) {
                var a = await _iicApiService.Geticconsumecode(data.cardno, $"{LoginInfo.Item3}099".ToInt32(0)).ConfigureAwait(false);
                var rnt = JsonConvert.DeserializeObject<ConsumecodeRsp>(a.content);
                var n = new { code = a.code, content = rnt, msg = a.msg };
                return new JsonResult(n);
            } else {
                return new JsonResult(new { code = -1, content = "", msg = "无此卡" });
            }
        }

        /// <summary>
        /// 检查会员消费码处理状态
        /// </summary>
        /// <param name="token">用户token</param>
        /// <param name="card">卡信息（cardno,consumecode</param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        [ProducesResponseType(typeof(Zmodel), (int)HttpStatusCode.OK)]
        [ProducesResponseType((int)HttpStatusCode.NotFound)]
        public async Task<IActionResult> Checkconsumecode([FromBody] CheckConsumecodeReq card, [FromHeader(Name = "u-token")]  string token)
        {
            if (card == null) {
                throw new ArgumentNullException(nameof(card));
            }

            var mobile = MemberHelper.GetMobile(token);
            ConsoleHelper.DoLog(card, Request);
            //var mcard = _cacheService.Get<MemberCard>("c_" + token);
            var command = new CheckConsumeCodeCommand(mobile, card.cardno, card.consumecode,LoginInfo.Item3) { RequestUrl = Request.GetShortUri(), UserIP = Request.GetUserIp() };
            var result = await _mediator.Send(command).ConfigureAwait(false);
            var rnt = JsonConvert.DeserializeObject<CheckConsumecodeRsp>(result.content);
            return Ok(new { code = result.code, content = rnt, msg = result.msg });
            //var a = await _iicApiService.icconsumecheck(card.cardno, card.consumecode);
            //// logger.Trace($"检查会员消费码处理状态:{a.ToString()}");
            //var rnt = JsonConvert.DeserializeObject<JObject>(a.content);
            //var n = new { code = a.code, content = rnt, msg = a.msg };
            //if (rnt != null)
            //{
            //    var je = rnt["money"].ToDecimal(-1);
            //    if (je > 0 && a.code == 301)
            //    {
            //        var s = _cacheService.Get<string>(Constant.CONSUMECODE + card.consumecode);
            //        if (string.IsNullOrEmpty(s))
            //        {
            //            _cacheService.Add(Constant.CONSUMECODE + card.consumecode, card.consumecode, TimeSpan.FromMinutes(1));
            //            var logdata = new UserLog { Url = Request.GetAbsoluteUri(), OPInfo = $"扫码支付,卡号:[{card.cardno}],支付码[{card.consumecode}]，支付金额{je}", OPTime = DateTime.Now, UserName = mobile, UserIP = Request.GetUserIp() };
            //            await _userLog.AddAsync<ICasaMielSession>(logdata);
            //        }
            //    }
            //}
            //return new JsonResult(n);
        }
        /// <summary>
        /// 会员绑卡
        /// </summary>
        /// <param name="data"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> MemberBindCard([FromBody] BindCardReq data, [FromHeader(Name = "u-token")]  string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            ConsoleHelper.DoLog(data, Request);
            var mobile = MemberHelper.GetMobile(token);
            if (mobile != data.Mobile) {
                return new JsonResult(new { code = "-1", msg = "手机号不符" });
            }
            var sucess = _mobileCheckCode.CheckCode(data.Mobile, data.Yzm, false);

            if (sucess["Success"].ToString().ToLower(CultureInfo.InvariantCulture) == "false") {
                return new JsonResult(new { code = "-1", msg = sucess["msg"].ToString() });
            }

            _cacheService.Remove(Constant.MYCARDS_PREFIX + mobile);
            var mcards = await _memberCard.GetListAsync<ICasaMielSession>(data.Mobile).ConfigureAwait(false);

            if (mcards == null) {
                var bandcard = await _iicApiService.Icregist(data.Cardno, data.Mobile, 15).ConfigureAwait(false);
                if (bandcard != null) {
                    if (bandcard.code == 0 || bandcard.code == 101 || bandcard.code == 103) {
                        var mcard = new MemberCard();
                        mcard.CardNO = data.Cardno;
                        mcard.Mobile = data.Mobile;
                        mcard.IsBind = true;
                        mcard.BindTime = DateTime.Now;
                        mcard.CreateTime = DateTime.Now;
                        mcard.Source = 15;
                        await _memberCard.AddAsync<ICasaMielSession>(mcard).ConfigureAwait(false);
                        //await _memberCard.UnitOfWork.SaveEntitiesAsync();
                    } else {
                        return new JsonResult(new { code = bandcard.code, msg = bandcard.msg });
                    }
                } else {
                    return new JsonResult(new { code = "-1", msg = "抱歉，请重试" });
                }
            } else {
                var list = mcards.Where(c => c.CardType != "3" && c.IsBind == true);
                if (list.Any()) {
                    return new JsonResult(new { code = "-1", msg = "您已经绑过卡" });
                }
                var entity = await _memberCard.FindAsync<ICasaMielSession>(data.Cardno, mobile).ConfigureAwait(false);
                var bandcard = await _iicApiService.Icregist(data.Cardno, data.Mobile, 15).ConfigureAwait(false);
                if (bandcard != null) {
                    if (bandcard.code == 0 || bandcard.code == 101 || bandcard.code == 103) {
                        if (entity == null) {
                            entity = new MemberCard {
                                CardNO = data.Cardno,
                                Mobile = data.Mobile,
                                IsBind = true,
                                BindTime = DateTime.Now,
                                CardType = "1",
                                Source = 15,
                                CreateTime = DateTime.Now
                            };
                            await _memberCard.AddAsync<ICasaMielSession>(entity).ConfigureAwait(false);
                        } else {
                            entity.IsBind = true;
                            entity.BindTime = DateTime.Now;
                            entity.Source = 15;
                            await _memberCard.UpdateAsync<ICasaMielSession>(entity).ConfigureAwait(false);
                            //await _memberCard.UnitOfWork.SaveChangesAsync();
                            // return new JsonResult(new { code = 0, content = "", msg = "绑卡成功！" });
                        }
                    } else {
                        return new JsonResult(new { code = bandcard.code, msg = bandcard.msg });
                    }
                }
                var logdata = new UserLog { Url = Request.GetShortUri(), OPInfo = $"绑会员卡,卡号:[{data.Cardno}]", OPTime = DateTime.Now, UserName = mobile, UserIP = Request.GetUserIp() };
                await _userLog.AddAsync<ICasaMielSession>(logdata).ConfigureAwait(false);

            }
            return new JsonResult(new { code = 0, content = "", msg = "绑卡成功！" });
        }
        /// <summary>
        /// 解绑，测试用
        /// </summary>
        /// <param name="data"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        [ProducesResponseType(typeof(Zmodel), (int)HttpStatusCode.OK)]
        [ProducesResponseType((int)HttpStatusCode.NotFound)]
        public async Task<IActionResult> Unicregist([FromBody] UnicCard data, [FromHeader(Name = "u-token")] string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            var a = await _iicApiService.Unicregist(data.cardno, data.mobile, 15).ConfigureAwait(false);
            var rnt = JsonConvert.DeserializeObject<JObject>(a.content);
            var n = new { code = a.code, content = rnt, msg = a.msg };
            return new JsonResult(n);
        }
        /// <summary>
        /// 解绑会员卡
        /// </summary>
        /// <param name="data"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        [ProducesResponseType(typeof(Zmodel), (int)HttpStatusCode.OK)]
        [ProducesResponseType((int)HttpStatusCode.NotFound)]
        public async Task<IActionResult> MemberUnicregist([FromBody] MemberUnicCardReq data, [FromHeader(Name = "u-token")] string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            ConsoleHelper.DoLog(data, Request);
            var mobile = MemberHelper.GetMobile(token);
            var sucess = await _mobileCheckCode.CheckSmsCodeAsync(mobile, data.yzm, true).ConfigureAwait(false);
            if (sucess["code"].ToString() != "0") {
                return new JsonResult(new { code = "-1", msg = sucess["msg"].ToString() });
            }
            // var mcard = _context.MemberCard.FirstOrDefault(c => c.Mobile == mobile && c.IsBind == true);
            var mcard = await _memberCard.FindAsync<ICasaMielSession>(data.cardno, mobile).ConfigureAwait(false);
            if (mcard == null) {
                //return BadRequest();
                return new JsonResult(new { code = 0, content = "", msg = "会员卡已经解绑" });
            }
            if (mcard.CardNO != data.cardno) {
                return new JsonResult(new { code = -1, content = "", msg = "卡号不存在" });
            }
            if (mcard.CardType == "2") {
                var result = await _iicApiService.GetCardBalance(data.cardno, $"{LoginInfo.Item3}099".ToInt32(0)).ConfigureAwait(false);
                if (result.code == 0) {
                    var vc = JsonConvert.DeserializeObject<JObject>(result.content);
                    if (Convert.ToDecimal(vc["directmoney"].ToString(), CultureInfo.CurrentCulture) > 0) {
                        return new JsonResult(new { code = -2, content = "", msg = "卡内有余额不能解绑！" });
                    }

                    //                "totalmoney": 598.01,
                    //"directmoney": 598.01,
                    //"othermoney": 0,
                }
            }
            var a = await _iicApiService.Unicregist(data.cardno, mcard.Mobile, 15).ConfigureAwait(false);
            var rnt = JsonConvert.DeserializeObject<JObject>(a.content);
            if (a.code == 0 || a.code == 103)//14手机号和会员卡号不匹配(已解）
            {
                mcard.IsBind = false;
                mcard.UnBindTime = DateTime.Now;
                await _memberCard.UpdateAsync<ICasaMielSession>(mcard).ConfigureAwait(false);
                //await _memberCard.UnitOfWork.SaveChangesAsync();
                _cacheService.Remove(Constant.MYCARDS_PREFIX + mobile);
                var logdata = new UserLog { Url = Request.GetShortUri(), OPInfo = $"解绑会员卡,卡号:[{data.cardno}]", OPTime = DateTime.Now, UserName = mobile, UserIP = Request.GetUserIp() };
                await _userLog.AddAsync<ICasaMielSession>(logdata).ConfigureAwait(false);
                return new JsonResult(new { code = 0, content = "", msg = "解绑成功！" });
            }

            var n = new { code = a.code, content = rnt, msg = a.msg };
            return new JsonResult(n);
        }

        /// <summary>
        /// 注册虚拟会员卡
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        [ProducesResponseType(typeof(Zmodel), (int)HttpStatusCode.OK)]
        [ProducesResponseType((int)HttpStatusCode.NotFound)]
        private async Task<IActionResult> IIcselfregist([FromHeader(Name = "u-token")] string token)
        {
            var mobile = MemberHelper.GetMobile(token);
            var mcards = await _memberCard.GetListAsync<ICasaMielSession>(mobile).ConfigureAwait(false);// _context.MemberCard.Where(c => c.Mobile == mobile).ToList();
            var list = mcards.Where(c => c.IsBind == true);
            if (list.Any()) {
                return new JsonResult(new { code = -1, msg = "您已经有会员卡，无需注册会员卡" });
            }
            var newcard = await _iicApiService.Icselfregist(mobile, 15).ConfigureAwait(false);
            var jobj = JsonConvert.DeserializeObject<JObject>(newcard.content);
            if (newcard.code == 0) {
                var mcard = new MemberCard {
                    CardNO = jobj["cardno"].ToString(),
                    Mobile = mobile,
                    CardType = "2",
                    IsBind = true,
                    BindTime = DateTime.Now,
                    Source = 15,
                    CreateTime = DateTime.Now
                };
                await _memberCard.AddAsync<ICasaMielSession>(mcard).ConfigureAwait(false);
                return new JsonResult(new { code = 1, data = new { CardNo = mcard.CardNO, CardType = mcard.CardType }, msg = "会员卡注册成功" });
            } else {
                var n = new { code = newcard.code, content = jobj, msg = newcard.msg };
                return new JsonResult(n);
            }
        }
        /// <summary>
        /// 注册新会员测试用
        /// </summary>
        /// <param name="data"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        [ProducesResponseType(typeof(Zmodel), (int)HttpStatusCode.OK)]
        [ProducesResponseType((int)HttpStatusCode.NotFound)]
        public async Task<IActionResult> Icselfregist([FromBody] UnicCard data, [FromHeader(Name = "u-token")] string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            var a = await _iicApiService.Icselfregist(data.mobile, 15).ConfigureAwait(false);
            var rnt = JsonConvert.DeserializeObject<JObject>(a.content);
            var n = new { code = a.code, content = rnt, msg = a.msg };
            return new JsonResult(n);
        }

        /// <summary>
        /// 会员申请会员卡
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpGet]
        [HttpPost]
        [Route("[action]")]
        [ProducesResponseType(typeof(Zmodel), (int)HttpStatusCode.OK)]
        [ProducesResponseType((int)HttpStatusCode.NotFound)]
        public async Task<IActionResult> MemberIcselfregist([FromHeader(Name = "u-token")] string token)
        {
            var mobile = MemberHelper.GetMobile(token);
            var cardlist = await _memberCard.GetListAsync<ICasaMielSession>(mobile).ConfigureAwait(false);// _context.MemberCard.Where(c => c.Mobile == mobile && c.IsBind == true);
            if (cardlist.Where(c => c.IsBind == true && c.CardType != "3").Any()) {
                return new JsonResult(new { code = -2, msg = "已有会员卡不能再申请" });
            }
            var result = await _iicApiService.Icselfregist(mobile, 15).ConfigureAwait(false);
            var rnt = JsonConvert.DeserializeObject<JObject>(result.content);
            if (result.code == 0) {
                _cacheService.Remove(Constant.MYCARDS_PREFIX + mobile);
                var mcard = await _memberCard.FindAsync<ICasaMielSession>(rnt["cardno"].ToString(), mobile).ConfigureAwait(false);
                if (mcard == null) {
                    mcard = new MemberCard {
                        CardNO = rnt["cardno"].ToString(),
                        Mobile = mobile,
                        IsBind = true,
                        CardType = "2",
                        Source = 15,
                        BindTime = DateTime.Now,
                        CreateTime = DateTime.Now
                    };
                    await _memberCard.AddAsync<ICasaMielSession>(mcard).ConfigureAwait(false);
                    var logdata = new UserLog { Url = Request.GetShortUri(), OPInfo = $"申请会员卡,卡号:[{rnt["cardno"].ToString()}]", OPTime = DateTime.Now, UserName = mobile, UserIP = Request.GetUserIp() };
                    await _userLog.AddAsync<ICasaMielSession>(logdata).ConfigureAwait(false);
                } else {
                    mcard.IsBind = true;
                    mcard.BindTime = DateTime.Now;
                    await _memberCard.UpdateAsync<ICasaMielSession>(mcard).ConfigureAwait(false);
                    //await _memberCard.UnitOfWork.SaveChangesAsync();
                    var logdata = new UserLog { Url = Request.GetShortUri(), OPInfo = $"重新申请会员卡,卡号:[{rnt["cardno"].ToString()}]", OPTime = DateTime.Now, UserName = mobile, UserIP = Request.GetUserIp() };
                    await _userLog.AddAsync<ICasaMielSession>(logdata).ConfigureAwait(false);
                }
                //var mcard = new MemberCard();
                //mcard.CardNo = rnt["cardno"].ToString();
                //mcard.Mobile = mobile;
                //mcard.IsBind = true;
                //mcard.CardType = "2";
                //mcard.BindTime = DateTime.Now;
                //mcard.CreateTime = DateTime.Now;
                //_memberCard.Add(mcard);
                //await _memberCard.UnitOfWork.SaveEntitiesAsync();
                //var logdata = new UserLog { Url = Request.GetAbsoluteUri(), OPInfo = $"申请会员卡,卡号:[{rnt["cardno"].ToString()}]", OPTime = DateTime.Now, UserName = mobile, UserIP = Request.GetUserIp() };
                //_userLog.Add(logdata);
                return new JsonResult(new { code = 1, msg = "会员卡申请成功", cardno = mcard.CardNO });
            }
            var n = new { code = result.code, content = rnt, msg = result.msg };
            return new JsonResult(n);
        }


        /// <summary>
        /// 绑卡测试用
        /// </summary>
        /// <param name="data"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        [ProducesResponseType(typeof(Zmodel), (int)HttpStatusCode.OK)]
        [ProducesResponseType((int)HttpStatusCode.NotFound)]
        public async Task<IActionResult> Icregist([FromBody] UnicCard data, [FromHeader(Name = "u-token")] string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            var a = await _iicApiService.Icregist(data.cardno, data.mobile, 15).ConfigureAwait(false);
            var rnt = JsonConvert.DeserializeObject<JObject>(a.content);
            var n = new { code = a.code, content = rnt, msg = a.msg };
            return new JsonResult(n);
        }
        /// <returns></returns>
        /// <summary>
        /// 查询会员卡消费和充值记录
        /// </summary>
        /// <remarks>
        /// {
        /// "code": 0,
        /// "content": [
        ///   {
        ///      "wxopenid": "",
        ///      "cardno": "276523218",
        ///     "shopid": "1",
        ///      "shopname": "玫隆皇冠测试",
        ///      "recdate": "2017-12-27 10:25:22",
        ///      "consumetype": "充值",
        ///      "tradeno": "C13S1G58221",
        ///      "totalmoney": 100,
        ///      "discountmoney": 0,
        ///      "realpaymoney": 100,
        ///      "directmoney": 100,
        ///      "othermoney": 0,
        ///      "point": 0
        ///    },
        ///    {
        ///      "wxopenid": "",
        ///      "cardno": "276523218",
        ///      "shopid": "1",
        ///      "shopname": "玫隆皇冠测试",
        ///      "recdate": "2017-12-27 10:25:36",
        ///      "consumetype": "充值",
        ///      "tradeno": "C13S1G58222",
        ///     "totalmoney": 100,
        ///      "discountmoney": 0,
        ///      "realpaymoney": 100,
        ///      "directmoney": 100,
        ///     "othermoney": 0,
        ///      "point": 0
        ///   },
        ///   {
        ///      "wxopenid": "",
        ///      "cardno": "276523218",
        ///      "shopid": "1",
        ///      "shopname": "玫隆皇冠测试",
        ///     "recdate": "2017-12-27 10:35:55",
        ///      "consumetype": "充值",
        ///      "tradeno": "C13S1G58223",
        ///      "totalmoney": 100,
        ///      "discountmoney": 0,
        ///      "realpaymoney": 100,
        ///     "directmoney": 100,
        ///      "othermoney": 0,
        ///      "point": 0
        ///    }
        /// ],
        ///  "msg": "处理成功"
        ///}
        ///</remarks>
        /// <param name="token">用户token</param>
        ///<param name="data">cardInfo</param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        [ProducesResponseType(typeof(Zmodel), (int)HttpStatusCode.OK)]
        [ProducesResponseType((int)HttpStatusCode.NotFound)]
        public async Task<IActionResult> GetICRecord([FromBody]CardInfoSearchReq data, [FromHeader(Name = "u-token")]  string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            var mobile = MemberHelper.GetMobile(token);
            var mcard = await _memberCard.GetListAsync<ICasaMielSession>(mobile).ConfigureAwait(false);

            if (mcard == null || !mcard.Where(c => c.IsBind == true).Any()) {
                return new JsonResult(new { code = -1, content = "", msg = "无此卡" });
            }
            List<IcRecordResponse> lists = new List<IcRecordResponse>();
            foreach (var item in mcard) {
                var a = await _iicApiService.GetIcRecord(item.CardNO, data.Startdate, data.Enddate,$"{LoginInfo.Item3}099".ToInt32(0)).ConfigureAwait(false);
                if (a.content.StartsWith("[")) {
                    //var rnt = JsonConvert.DeserializeObject<JArray>(a.content);
                    var list = JsonConvert.DeserializeObject<List<IcRecordResponse>>(a.content);
                    // list = list.OrderByDescending(i => i.recdate).ToList();
                    lists = lists.Concat(list).ToList();
                }
                //else
                //{
                //    var rnt = JsonConvert.DeserializeObject<JObject>(a.content);
                //    var n = new { code = a.code, content = rnt, msg = a.msg };
                //    return new JsonResult(n);
                //}
            }
            if (lists.Count > 0) {
                lists = lists.OrderByDescending(i => i.recdate).ToList();
            }
            var n = new { code = 0, content = lists, msg = "" };
            return new JsonResult(n);
            //var a = await _iicApiService.GetIcRecord(data.cardno, data.startdate, data.enddate);
            //if (a.content.StartsWith("["))
            //{
            //    //var rnt = JsonConvert.DeserializeObject<JArray>(a.content);
            //    var list = JsonConvert.DeserializeObject<List<IcRecordResponse>>(a.content);
            //    list = list.OrderByDescending(i => i.recdate).ToList();
            //    var n = new { code = a.code, content = list, msg = a.msg };
            //    return new JsonResult(n);
            //}
            //else
            //{
            //    var rnt = JsonConvert.DeserializeObject<JObject>(a.content);
            //    var n = new { code = a.code, content = rnt, msg = a.msg };
            //    return new JsonResult(n);
            //}
        }

        /// <summary>
        /// 测试消费记录---- 测试用
        /// </summary>
        /// <param name="cardno"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> GetIcRecordTest(string cardno, [FromHeader(Name = "u-token")]  string token)
        {
            var a = await _iicApiService.GetIcRecord(cardno, DateTime.Now.AddDays(-30), DateTime.Now, $"{LoginInfo.Item3}099".ToInt32(0)).ConfigureAwait(false);
            if (a.content.StartsWith("[")) {
                //var rnt = JsonConvert.DeserializeObject<JArray>(a.content);
                var list = JsonConvert.DeserializeObject<List<IcRecordResponse>>(a.content);
                list = list.OrderByDescending(i => i.recdate).ToList();

                var n = new { code = a.code, content = list, msg = a.msg };
                return new JsonResult(n);
            } else {
                var rnt = JsonConvert.DeserializeObject<JObject>(a.content);
                var n = new { code = a.code, content = rnt, msg = a.msg };
                return new JsonResult(n);
            }
        }
        /// <summary>
        /// 二维码查询
        /// </summary>
        /// <param name="data"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        /// <remarks>
        /// {
        ///"code":0,
        /// "msg":"处理成功",
        /// "content":"
        /// {
        /// "cardno":"xxxx",
        /// "phoneno";"xxxx",
        /// "wxopenid":"xxxx",
        /// "qrcodetype":1,
        /// "qrcodetypedesc":"充值",
        /// "chargemoney":xx.xx,
        /// "largessmoney":x.xx,
        /// "point":xxx,
        /// "tickets":
        ///  [
        /// {
        /// "ticketname":"xxxx",
        /// "ticketid”:xxxx,
        /// "je":xxx.xx,
        /// "makedate","yyyy-mm-dd",
        /// "startdate","yyyy-mm-dd",
        /// "enddate","yyyy-mm-dd",
        /// "description",""	
        ///   },
        /// {
        /// "ticketname”:”xxxx”,
        /// "ticketid”:xxxx,
        /// "je”:xxx.xx,
        /// "makedate”,”yyyy-mm-dd”,
        /// "startdate”,”yyyy-mm-dd”,
        /// "enddate”,”yyyy-mm-dd”,
        /// "description”,””	
        ///  },
        /// …
        /// ]
        ///   }",
        ///  }
        /// 
        /// </remarks>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> Icqrcodequery([FromBody]IcQrcodeChargeReq data, [FromHeader(Name = "u-token")]  string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            var mobile = MemberHelper.GetMobile(token);
            var a = await _iicApiService.IcQrcodeQuery(data.Cardno, mobile, data.Qrcode).ConfigureAwait(false);
            var rnt = JsonConvert.DeserializeObject<JObject>(a.content);
            var n = new { code = a.code, content = rnt, msg = a.msg };
            return new JsonResult(n);
        }
        /// <summary>
        /// 二维码使用
        /// </summary>
        /// <param name="data"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        /// <remarks>
        /// {
        ///"code":0,
        ///"msg":"处理成功", 
        ///"content":"
        ///{
        ///"cardno":"xxxx",
        ///"phoneno";"xxxx",
        ///"wxopenid":"xxxx",
        ///"qrcodetype":"1",
        ///"chargemoney":xx.xx,
        ///"largessmoney":x.xx,
        ///"point":xxx,
        ///"tickets":
        ///[
        ///{
        ///"ticketname":"xxxx",
        ///"ticketid":xxxx,
        ///"je":xxx.xx,
        ///"makedate","yyyy-mm-dd",
        ///"startdate","yyyy-mm-dd",
        ///"enddate","yyyy-mm-dd",
        ///"description",""	
        ///},
        ///{
        ///"ticketname":"xxxx",
        ///"ticketid":xxxx,
        ///"je":xxx.xx,
        ///"makedate","yyyy-mm-dd",
        ///"startdate","yyyy-mm-dd",
        ///"enddate","yyyy-mm-dd",
        ///"description",""	
        ///},
        ///…
        ///]
        ///}",
        ///"sign":"9ade8ba90cf38745bea56398d235daae"
        ///}
        /// </remarks>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> icqrcodeverify([FromBody]IcQrcodeChargeReq data, [FromHeader(Name = "u-token")]  string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            var mobile = MemberHelper.GetMobile(token);


            var command = new GiftCardReChargeCommand(data.Cardno, data.Qrcode, mobile, $"{LoginInfo.Item3}099".ToInt32(0)) { RequestUrl = Request.GetShortUri(), UserIP = Request.GetUserIp() };
            var result = await _mediator.Send(command).ConfigureAwait(false);
            return Ok(result);

            //var mcard = await _memberCard.GetCardListAsyncByMobile<ICasaMielSession>(mobile);

            //         string cardno = "";
            //         var ar = mcard.Where(c => c.CardType == "3").SingleOrDefault();
            //         if (ar != null)
            //         {
            //             cardno = ar.CardNo;
            //         }
            //         var send = _mobileCheckCode.CheckCode(mobile, data.yzm, true);
            //         if (send["Success"].ToString().ToLower() == "false")
            //         {
            //             return new JsonResult(new { code = "-1", msg = send["msg"].ToString() });
            //         }
            //         var a = await _iicApiService.icqrcodeverify(cardno, mobile, data.qrcode);

            //         var rnt = JsonConvert.DeserializeObject<JObject>(a.content);
            //         if (a.code == 0 && cardno == "")
            //         {
            //             ar = new MemberCard { CardNo = rnt["cardno"].ToString(), CardType = "3", IsBind = true, BindTime = DateTime.Now, CreateTime = DateTime.Now, Mobile = mobile };
            //             await _memberCard.AddAsync<ICasaMielSession>(ar);
            //         }
            //         var n = new { code = a.code, content = rnt, msg = a.msg };
            //         _cacheService.Remove(Constant.MYCARDS_PREFIX + mobile);
            //         return new JsonResult(n);
        }
        /// <summary>
        /// 会员卡充值
        /// </summary>
        /// <remarks>
        /// {
        ///"code": 0,
        /// "content": {
        /// "wxopenid": "",
        /// "cardno": "276523218",
        /// "tradeno": "C13S1G58224",
        ///"chargemoney": 50,
        ///"largessmoney": 0,
        ///"point": 0,
        /// "ticket": []
        ///},
        /// "msg": "处理成功"
        ///}
        /// </remarks>
        /// <param name="cardCharge"></param>
        /// <param name="token">用户token</param>
        /// <param name="auth"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        [ProducesResponseType(typeof(Zmodel), (int)HttpStatusCode.OK)]
        [ProducesResponseType((int)HttpStatusCode.NotFound)]
        public ActionResult IcCharge([FromBody] CardChargeReq cardCharge, [FromHeader(Name = "u-token")]  string token, [FromHeader(Name = "auth")] string auth)
        {
            if (cardCharge == null) {
                throw new ArgumentNullException(nameof(cardCharge));
            }

            if (auth != "stonesh") return Ok("");
            var b = _iicApiService.IcChargeSync(cardCharge.cardno, cardCharge.chargemoney, cardCharge.paytype, cardCharge.paytradeno);
            ConsoleHelper.DoLog(cardCharge, Request);
            var rnt1 = JsonConvert.DeserializeObject<JObject>(b.content);
            var n1 = new { code = b.code, content = rnt1, msg = b.msg };
            return new JsonResult(n1);

        }
    }
}